# -*- coding:utf-8 -*-
'''
@Author: lindes
'''

import random
import string
import hashlib
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from django.conf.global_settings import SECRET_KEY
from django.http import JsonResponse


def verify_code(length):
    """
    生成数字验证码
    :param length: 验证码长度
    :return: code
    """
    return ''.join(random.sample(string.digits, length))


def md5_hex(pwd):
    """
    本站专用md5哈希密码摘要处理函数
    :param pwd: 原文密码
    :return: 密文密码
    """
    md5 = hashlib.md5()
    md5.update((pwd + SECRET_KEY).encode('utf-8'))
    return md5.hexdigest()


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def send_mail(to_addr, code):
    smtp_server = "smtp.163.com"

    sender = "18826131701@163.com"

    password = "LDS18826131701"

    to_addr = to_addr

    msg = MIMEMultipart()

    msg['Subject'] = Header("邮箱验证码", "utf-8").encode()

    msg["From"] = _format_addr("篮球社区<%s>" % sender)

    msg['To'] = _format_addr("用户<%s>" % to_addr)

    msg.attach(MIMEText(f'<html><body><h1>您的邮箱验证码是{code}</h1></body></html>', 'html', 'utf-8'))

    mailServer = smtplib.SMTP(smtp_server, 25)

    mailServer.set_debuglevel(1)

    mailServer.login(sender, password)
    try:
        mailServer.sendmail(sender, [to_addr], msg.as_string())
    except Exception as e:
        is_send = False
    else:
        is_send = True
    mailServer.quit()
    return is_send


if __name__ == '__main__':
    # print(create_token())
    # print(verify_code(4))
    print(md5_hex('123456'))
    # send_mail()
